package com.djmw.mouse.service;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springside.modules.persistence.DynamicSpecifications;
import org.springside.modules.persistence.SearchFilter;
import org.springside.modules.persistence.SearchFilter.Operator;

import com.djmw.mouse.entity.Department;
import com.djmw.mouse.repository.DepartmentDao;

//Spring Bean的标识.
@Component
// 默认将类中的所有public函数纳入事务管理.
@Transactional(readOnly = true)
public class DepartmentService {

	@Autowired
	private DepartmentDao departmentDao;

	public Department getDepartment(Long id) {
		return departmentDao.findOne(id);
	}

	@Transactional(readOnly = false)
	public void saveDepartment(Department entity) {
		departmentDao.save(entity);
	}

	@Transactional(readOnly = false)
	public void deleteDepartment(Long id) {
		departmentDao.delete(id);
	}

	public Page<Department> getCompanyDepartment(Long companyId, Map<String, Object> searchParams, int pageNumber,
			int pageSize, String sortType) {
		PageRequest pageRequest = buildPageRequest(pageNumber, pageSize, sortType);
		Specification<Department> spec = buildSpecification(companyId, searchParams);

		return departmentDao.findAll(spec, pageRequest);
	}

	public Page<Department> getAllCompanyDepartment(Long companyId) {
		return getCompanyDepartment(companyId, new HashMap<String, Object>(), 1, 100, "auto");
	}

	/**
	 * 创建分页请求.
	 */
	private PageRequest buildPageRequest(int pageNumber, int pagzSize, String sortType) {
		Sort sort = null;
		if ("auto".equals(sortType)) {
			sort = new Sort(Direction.DESC, "id");
		} else if ("name".equals(sortType)) {
			sort = new Sort(Direction.ASC, "name");
		}

		return new PageRequest(pageNumber - 1, pagzSize, sort);
	}

	/**
	 * 创建动态查询条件组合.
	 */
	private Specification<Department> buildSpecification(Long companyId, Map<String, Object> searchParams) {
		Map<String, SearchFilter> filters = SearchFilter.parse(searchParams);
		filters.put("company.id", new SearchFilter("company.id", Operator.EQ, companyId));
		Specification<Department> spec = DynamicSpecifications.bySearchFilter(filters.values(), Department.class);
		return spec;
	}
}
